package com.satan.juc.demo11;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author: Demon
 * @Date: 2024/3/28 21:47
 * @Description:
 **/
public class ReentrantReadWriteLockDemo {
    private final ReentrantReadWriteLock lock=new ReentrantReadWriteLock();
    private final ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
    private final ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
    private int data;
    // 写入数据
    public void writeData(int newData) {
        writeLock.lock();
        try {
            data = newData;
            System.out.println("Data is updated by " + Thread.currentThread().getName());
        } finally {
            writeLock.unlock();
        }
    }
    // 读取数据
    public int readData() {
        readLock.lock();
        try {
            return data;
        } finally {
            readLock.unlock();
        }
    }
    public static void main(String[] args) {
        ReentrantReadWriteLockDemo example = new ReentrantReadWriteLockDemo();

        // 线程1写入数据
        new Thread(() -> {
            example.writeData(42);
        }, "Writer1").start();

        // 线程2读取数据
        new Thread(() -> {
            int readData = example.readData();
            System.out.println("Data is read by " + Thread.currentThread().getName() + ": " + readData);
        }, "Reader1").start();

        // 线程3写入数据
        new Thread(() -> {
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
            example.writeData(13);
        }, "Writer2").start();

        // 线程4读取数据
        new Thread(() -> {
            int readData = example.readData();
            System.out.println("Data is read by " + Thread.currentThread().getName() + ": " + readData);
        }, "Reader2").start();
    }

}
